<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>单价配置</div>
        <div class="flex">
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          width="160"
          label="申请编号"
          prop="applicationNo"
          key="申请编号"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          width="200"
          label="公司结算单价（元/㎡）"
          key="公司结算单价（元/㎡）"
          sortable
          prop="companySettlementPrice"
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column
          width="200"
          label="团队结算单价（元/㎡）"
          key="团队结算单价（元/㎡）"
          sortable
          prop="teamSettlementPrice"
          v-if="header_list[2].showTable"
        ></el-table-column>
        <el-table-column
          label="设计经理结算单价（元/㎡）"
          width="200"
          key="设计经理结算单价（元/㎡）"
          sortable
          prop="managerSettlementPrice"
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column
          width="200"
          label="设计组长结算单价（元/㎡）"
          key="设计组长结算单价（元/㎡）"
          sortable
          prop="teamLeaderSettlementPrice"
          v-if="header_list[4].showTable"
        ></el-table-column>
        <el-table-column
          label="启用日期"
          key="启用日期"
          sortable
          prop="isDelete"
          v-if="header_list[5].showTable"
          ><template #default="scope">
            <div v-if="scope.row.activationDate ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.activationDate), 'YYYY-MM-DD') }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column
          label="结束日期"
          key="结束日期"
          sortable
          prop="isDelete"
          v-if="header_list[6].showTable"
          ><template #default="scope">
            <div v-if="scope.row.endDate ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.endDate), 'YYYY-MM-DD') }}
            </div>
            <div v-else>不限</div>
          </template></el-table-column
        >
        <el-table-column
          label="备注"
          key="备注"
          sortable
          prop="remark"
          show-overflow-tooltip
          v-if="header_list[7].showTable"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope: any">
            <el-button @click="edit_list(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="30%"
    destroy-on-close
    @close="resetForm(addUnitPriceform)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增单价</h4>
      <h4 v-else>编辑单价</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addUnitPriceform"
        :rules="unitPrice_rules"
        label-width="160px"
      >
        <el-form-item label="公司结算价格" prop="companySettlementPrice">
          <el-input-number
            :max="10000"
            :min="0"
            v-model="add_form_data.companySettlementPrice"
            placeholder="请输入"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="团队结算价格" prop="teamSettlementPrice">
          <el-input-number
            :max="10000"
            :min="0"
            v-model="add_form_data.teamSettlementPrice"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="设计经理结算价格" prop="managerSettlementPrice">
          <el-input-number
            :max="10000"
            :min="0"
            v-model="add_form_data.managerSettlementPrice"
            placeholder="请输入"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="设计组长结算价格" prop="teamLeaderSettlementPrice">
          <el-input-number
            :max="10000"
            :min="0"
            v-model="add_form_data.teamLeaderSettlementPrice"
            placeholder="请输入"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="启用日期" prop="activationDate">
          <el-date-picker
            v-model="add_form_data.activationDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
            placeholder="请选择"
            @change="
              () => {
                add_form_data.endDate =
                  add_form_data.activationDate > add_form_data.endDate
                    ? ''
                    : add_form_data.endDate
              }
            "
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="add_form_data.endDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
            placeholder="请选择"
            :disabled="add_form_data.activationDate == ''"
            :disabled-date="disabledEnable"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="add_form_data.remark"
            placeholder="请输入"
            type="textarea"
            show-word-limit
            maxlength="300"
          ></el-input>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetForm(addUnitPriceform)">取消</el-button>
          <el-button type="primary" @click="submit_unitPrice(addUnitPriceform)"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { check_role, formatDate, handle_search_key } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'
const addUnitPriceform = ref<FormInstance>()
const unitPrice_rules = ref({
  // 表单验证规则
  companySettlementPrice: [
    { required: true, message: '请输入公司结算单价', trigger: 'blur' },
  ],
  managerSettlementPrice: [
    { required: true, message: '请输入设计经理结算单价', trigger: 'blur' },
  ],
  teamLeaderSettlementPrice: [
    { required: true, message: '请输入设计组长结算单价', trigger: 'blur' },
  ],
  teamSettlementPrice: [
    { required: true, message: '请输入团队结算单价', trigger: 'blur' },
  ],
  activationDate: [
    { required: true, message: '请选择启用日期', trigger: 'change' },
  ],
})
const list = ref()
const max_height = ref()
const disabledEnable = (time) => {
  return time.getTime() < add_form_data.value.activationDate
}
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '申请编号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '公司结算单价（元/㎡）',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: true,
    options: [],
  },
  {
    label: '团队结算单价（元/㎡）',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '设计经理结算单价（元/㎡）',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '设计组长结算单价（元/㎡）',
    value: ['', ''],
    showTable: true,
    type: 'input_number',
    isShow: false,
    options: [],
  },
  {
    label: '启用日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '结束日期',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  applicationNo: '',
  activationDate: '',
  endDate: '',
  remark: '',
  companySettlementPrice: '',
  managerSettlementPrice: '',
  teamLeaderSettlementPrice: '',
  teamSettlementPrice: '',
})
const add_form_data = ref({
  activationDate: '',
  applicationDate: '',
  endDate: '',
  remark: '',
  companySettlementPrice: '',
  managerSettlementPrice: '',
  teamLeaderSettlementPrice: '',
  teamSettlementPrice: '',
  id: '',
})
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  setTimeout(() => {
    get_list()
  }, 100)
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const submit_unitPrice = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.unitPriceConfig
              : serviceApi.unitPriceConfig + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            get_list()
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const edit_list = (e) => {
  add_form_data.value = {
    activationDate: parseInt(e.activationDate) as any,
    applicationDate: parseInt(e.applicationDate) as any,
    endDate: parseInt(e.endDate) as any,
    remark: e.remark,
    companySettlementPrice: e.companySettlementPrice,
    managerSettlementPrice: e.managerSettlementPrice,
    teamLeaderSettlementPrice: e.teamLeaderSettlementPrice,
    teamSettlementPrice: e.teamSettlementPrice,
    id: e.id,
  }
  show_box.value = true
}
const btn_loading = ref(false)
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.unitPriceConfig + '/list',
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      list.value = res.data
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const search_key = () => {
  page_data.value = {
    applicationNo: header_list.value[0].value,
    companySettlementPrice: header_list.value[1].value,
    teamSettlementPrice: header_list.value[2].value,
    managerSettlementPrice: header_list.value[3].value,
    teamLeaderSettlementPrice: header_list.value[4].value,
    activationDate: header_list.value[5].value,
    endDate: header_list.value[6].value,
    remark: header_list.value[7].value,
  }
  get_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  console.log(123)
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    activationDate: '',
    applicationDate: '',
    endDate: '',
    remark: '',
    companySettlementPrice: '',
    managerSettlementPrice: '',
    teamLeaderSettlementPrice: '',
    teamSettlementPrice: '',
    id: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
